import Datastore from 'lowdb'
import FileSync from 'lowdb/adapters/FileSync'
import crypto from 'crypto'
import path from 'path'
import { STORE_PATH } from './const'

function encrypt(data) {
  const cipher = crypto.createCipher('aes-128-ecb', '1967988842')
  let encrypted = cipher.update(data, 'utf8', 'hex')
  encrypted += cipher.final('hex')
  return encrypted
}

function decrypt(data) {
  const decipher = crypto.createDecipher('aes-128-ecb', '1967988842')
  let decrypted = decipher.update(data, 'hex', 'utf8')
  decrypted += decipher.final('utf8')
  return decrypted
}

// noinspection JSUnusedGlobalSymbols
const adapter = new FileSync(path.join(STORE_PATH, '/db.data'), {
  serialize: (data) => encrypt(JSON.stringify(data)),
  deserialize: (data) => JSON.parse(decrypt(data))
})

const db = Datastore(adapter)

/* 初始化用户数据*/
if (!db.has('user').value()) {
  db.set('user', {}).write()
}

/* 初始化服务器数据*/
if (!db.has('config').value()) {
  db.set('config', {
    language: '简体中文',
    serverIp: 'localhost',
    datastorePath: STORE_PATH,
    smMethod: 'Enter'
  }).write()
}

export default db
